#include "rrrenderer.h"
#include <cstdio>
#include <cstring>

void RRRenderer::rrDraw(RRPrim *arg, SDL_Surface *screen)
{
    Uint32 color;

    memcpy(&prim1, arg, sizeof(RRPrim));
    yrotater.rrRotateY(&prim1);
    zmover.rrMoveZ(&prim1);
    //diffuser.rrDiffue(&prim1);
    shader.rrShading(&prim1);
    projector.rrProjectiveTrans(&prim1);
    clipping.rrClipping(&prim1, &prim2);
    viewport.rrViewportTrans(&prim2);
    rasterizer.rrSetPrim(prim2);
    rasterizer.rrRast();

    int pnum;
    pnum = rrGetPointsNum();
    for(int i=0; i<pnum; i++) {
        RRFragment point;
        point = rrGetPoint(i);
        if(depthtester.rrDepthTest(point.x, point.y, point.z)) {
            color = SDL_MapRGB(screen->format, (int)(point.c[1] * 255), (int)(point.c[2] * 255), (int)(point.c[3] * 255));
            Uint32 *bufp;
            bufp = (Uint32 *)screen->pixels + point.y * screen->pitch/4 + point.x;
            *bufp = color;
        }
    }
}

void RRRenderer::rrDraw(RRVertexArray *arg, SDL_Surface *screen)
{
    int e_num;
    RRPrim prim;
    e_num = arg->rrGetElemNum();
    for(int i=0; i<e_num; i++) {
        arg->rrGetPrim(i, &prim);
        rrDraw(&prim, screen);
    }
}

int RRRenderer::rrGetPointsNum()
{
    return rasterizer.rrGetPointsNum();
}

RRFragment RRRenderer::rrGetPoint(int index)
{
    return rasterizer.rrGetPoint(index);
}

void RRRenderer::rrPrintVert(int index)
{
    RRVertex temp;
    temp = prim2.rrGetVert(index);
    printf("%f, %f, %f\n", temp.x, temp.y, temp.z);
    printf("%f, %f, %f, %f\n", temp.c[0], temp.c[1], temp.c[2], temp.c[3]);
}

void RRRenderer::rrPrintRast()
{
    RRFragment temp;
    int pnum;
    pnum = rasterizer.rrGetPointsNum();
    for(int i=0; i<pnum; i++) {
        temp = rasterizer.rrGetPoint(i);
        printf("%d %d %f %f %f\n", temp.x, temp.y, temp.c[1], temp.c[2], temp.c[3]);
    }
}

void RRRenderer::rrRotateY(float deg)
{
    yrotater.rrSetDegree(deg);
}

void RRRenderer::rrFlash()
{
    depthtester.rrFlash();
}
